package com.horsen.service.aliyun.controller.admin;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.horsen.common.util.R;
import com.horsen.common.util.ResultCodeEnum;
import com.horsen.service.base.exception.HseduException;
import com.horsen.service.base.util.ExceptionUtils;
import com.horsen.service.aliyun.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * 文件 控制器
 *
 * @author Horsen
 */
@Api(tags = "阿里云OSS文件管理")
@Slf4j
@RestController
@RequestMapping("/admin/aliyun/oss")
public class FileController {
    @Autowired
    private FileService fileService;

    @ApiOperationSupport(order = 1)
    @ApiOperation("上传文件至阿里云OSS")
    @PostMapping("/{module}")
    public R upload(@ApiParam(value = "文件", required = true) MultipartFile file,
                    @ApiParam(value = "模块名", required = true)
                    @PathVariable("module") String module) {
        try {
            InputStream inputStream = file.getInputStream();
            String filename = file.getOriginalFilename();
            String url = fileService.upload(inputStream, module, filename);
            return R.ok("文件上传成功").setData("url", url);
        } catch (Exception e) {
            log.error(ExceptionUtils.getMessage(e));
            // 抛出文件上传错误
            throw new HseduException(ResultCodeEnum.FILE_UPLOAD_ERROR);
        }
    }

    @ApiOperationSupport(order = 2)
    @ApiOperation("从阿里云OSS删除文件")
    @PostMapping("/")
    public R delete(@ApiParam(value = "文件URL", required = true)
                    @RequestBody String url) {
        fileService.deleteFile(url);
        return R.ok("从OSS删除文件成功");
    }
}
